package com.bw.common

import android.app.Application
import android.content.Context
import androidx.room.Room
import com.bw.common.common.WSMsgType
import com.bw.common.db.IVideoDataBase
import com.bw.common.event.WSReceiveEvent
import com.bw.common.utils.LogUtils
import com.bw.common.websocket.WebSocketUtils
import org.greenrobot.eventbus.EventBus
import org.java_websocket.handshake.ServerHandshake

/**
 * @author:created by hahajing
 * 时间：2024/4/24 0024
 * 企鹅号:444511958
 * 描述:
 */
abstract class BaseApplication:Application() {


    override fun onCreate() {
        super.onCreate()
        mContext=this

        db = Room.databaseBuilder(
            applicationContext,
            IVideoDataBase::class.java, "ivideo_db"
        ).build()

        websocket=WebSocketUtils.Builder()
            .setListener(object :WebSocketUtils.ReceiveMsgListener{
                override fun onReceive(message: String?) {
                    LogUtils.d("123","onReceive content->${message}")
                    EventBus.getDefault().post(WSReceiveEvent(WSMsgType.RECEIVE,message!!))
                }

                override fun onOpen(handshakedata: ServerHandshake?) {
                    LogUtils.d("123","onOpen")
                    EventBus.getDefault().post(WSReceiveEvent(WSMsgType.OPEN,""))
                }

                override fun onError(ex: Exception?) {
                    LogUtils.d("123","error -> ${ex?.message}")
                    EventBus.getDefault().post(WSReceiveEvent(WSMsgType.ERROR,ex?.message!!))
                }

                override fun onClose(code: Int, reason: String?, remote: Boolean) {
                    LogUtils.d("123","onClose")
                    EventBus.getDefault().post(WSReceiveEvent(WSMsgType.CLOSE,reason!!))
                }

            })
            .build()
    }

    companion object{
        private lateinit var db:IVideoDataBase
        private lateinit var mContext: Context
        private lateinit var websocket:WebSocketUtils

        fun getDB():IVideoDataBase{
            return db
        }

        /**
         * 获取Application Context
         */
        fun getApplicationContext():Context{
            return mContext
        }

        /**
         * 获取websocketutils
         */
        fun getWebSocket():WebSocketUtils{
            return websocket
        }
    }
}